<script setup lang="ts">
import { ref, watch } from 'vue';
import { useIntersectionObserver } from '@vueuse/core';

const target = ref(null);
const root = ref(null);
const targetIsVisible = ref(false);

const { isActive, isSupported, resume, pause, stop } = useIntersectionObserver(
  target,
  ([{ isIntersecting }]) => {
    targetIsVisible.value = isIntersecting;
  },
  { root }
);

const radioDisabled = ref(false);

const clickStop = () => {
  stop();
  radioDisabled.value = true;
};

watch(
  () => isActive.value,
  (value) => {
    if (value) {
      resume();
    } else {
      pause();
    }
  }
);
</script>

<template>
  <div class="ml-1 mt-1">
    <el-alert
      :title="'是否可用 useIntersectionObserver: ' + isSupported"
      type="success"
    />
    <el-row align="bottom">
      <el-col :span="3">
        <el-radio-group v-model="isActive" :disabled="radioDisabled">
          <el-radio-button :label="true" size="small" border>
            监听
          </el-radio-button>
          <el-radio-button :label="false" size="small" border>
            不监听
          </el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="3">
        <el-button size="small" type="danger" class="ml-1" @click="clickStop">
          停止监听
        </el-button>
      </el-col>
    </el-row>
  </div>

  <div class="root" ref="root">
    <span>Scroll me down</span>
    <span></span>
    <span></span>
    <span></span>
    <h4 ref="target">Hello word</h4>
    <span></span>
    <span></span>
    <span></span>
    <span>Scroll me up</span>
  </div>
  <el-alert
    v-show="!radioDisabled"
    :title="'Hello word 是否在视线范围: ' + targetIsVisible"
    :type="targetIsVisible ? 'success' : 'error'"
  />

  <div>杨艺</div>
</template>
<style scoped>
.root {
  height: 150px;
  overflow-y: auto;
  border: 1px dotted salmon;
  margin: 10px;
  span {
    height: 40px;
    display: block;
  }
}
h4 {
  border: 1px dotted seagreen;
  margin: 20px;
}
.ml-1 {
  margin-left: 10px;
}
.mt-1 {
  margin-top: 10px;
}
</style>
